package com.zbkj.crmeb.merchant.admin.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CommonPage;
import com.crmeb.core.common.CommonResult;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.utils.CrmebUtil;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.model.ChannelMerchantAccount;
import com.zbkj.crmeb.chant.model.ChannelMerchantDistribution;
import com.zbkj.crmeb.chant.request.*;
import com.zbkj.crmeb.chant.response.AccountCenterResponse;
import com.zbkj.crmeb.chant.response.ChannelMerchantPurchaseResponse;
import com.zbkj.crmeb.chant.response.DistributionResponse;
import com.zbkj.crmeb.chant.response.SupplierAccountCenterResponse;
import com.zbkj.crmeb.chant.service.ChannelMerchantDistributionService;
import com.zbkj.crmeb.chant.service.IChannelMerchantAccountService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.chant.vo.ChannelMerchantVO;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.front.request.UserRechargeRequest;
import com.zbkj.crmeb.order.pprocess.AdapayDegreePayOrderProcess;
import com.zbkj.crmeb.store.request.StoreOrderRefundRequest;
import com.zbkj.crmeb.system.model.SystemConfig;
import com.zbkj.crmeb.system.request.PaymentAccountRequest;
import com.zbkj.crmeb.system.service.SystemConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * 渠道商户
 */
@Slf4j
@RestController("MerChannelMerchantController")
@RequestMapping("api/chant/mer/channel-merchant")
@Api(tags = "商户后台-渠道商户配置")
public class MerChannelMerchantController extends AdminBaseController {

    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private IChannelMerchantAccountService channelMerchantAccountService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private ChannelMerchantDistributionService channelMerchantDistributionService;
    @Value("${server.wechatProgramToken}")
    private Boolean refundFlag;


    /**
     * 当前商户详情
     * @return
     */
    @ApiOperation(value = "当前商户详情")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public CommonResult<ChannelMerchantVO> merchantList(HttpServletRequest request){
        ChannelMerchant channelMerchant = channelMerchantService.getById(getMerId(request));
        ChannelMerchantAccount account = channelMerchantAccountService.getOne(Wrappers.<ChannelMerchantAccount>lambdaQuery()
                .eq(ChannelMerchantAccount :: getMerId, channelMerchant.getId())
                .last("LIMIT 1")
                );
        ChannelMerchantVO channelMerchantVO = new ChannelMerchantVO();
        BeanUtils.copyProperties(channelMerchant, channelMerchantVO);
        BeanUtils.copyProperties(account, channelMerchantVO,"id");

        // 商户自定义配置
        SystemConfig config = systemConfigService.getMerchantCustomConfig(channelMerchant.getId(), Constants.CONFIG_INDEX);
        channelMerchantVO.setIndexConfig(null == config ? "1" : config.getValue());

        SystemConfig configProductDetail = systemConfigService.getMerchantCustomConfig(channelMerchant.getId(), Constants.CONFIG_PRODUCT_DETAIL);
        channelMerchantVO.setProductDetailConfig(null == configProductDetail ? "0" : configProductDetail.getValue());

        SystemConfig systemConfig = systemConfigService.getMerchantCustomConfig(channelMerchant.getId(), Constants.CONFIG_KEY_SHOW_DISCOUNT);
        channelMerchantVO.setShowDiscount((Objects.isNull(systemConfig) || "1".equals(systemConfig.getValue()) ? 1 : 0));

        SystemConfig showSupplierConfig = systemConfigService.getMerchantCustomConfig(channelMerchant.getId(), Constants.CONFIG_KEY_SHOW_SUPPLIER);
        channelMerchantVO.setShowSupplier(Objects.isNull(showSupplierConfig) ? 0 : Integer.parseInt(showSupplierConfig.getValue()));
        return CommonResult.success(channelMerchantVO);
    }

    /**
     * 修改渠道商户
     */
    @ApiOperation(value = "修改渠道商户店铺/物流介绍图")
    @RequestMapping(value = "/updateImage", method = RequestMethod.POST)
    public CommonResult<Boolean> updateMerchant(@RequestBody ChannelMerchant entity,HttpServletRequest request){
        entity.setId(getMerId(request));
        return CommonResult.success(channelMerchantService.updateById(entity));
    }

    @ApiOperation(value = "商户提现")
    @PostMapping("/withdraw/offline")
    public CommonResult<String> offlineWithdraw(@RequestBody UserRechargeRequest userRechargeRequest, HttpServletRequest request){
        boolean b = channelMerchantAccountService.offlineWithdrawApply(getMerId(request), userRechargeRequest.getPrice(), CrmebUtil.getClientIp(request));
    
        if(b){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }

    @ApiOperation(value = "渠道商户账户中心")
    @GetMapping(value = "/account/center")
    public CommonResult<AccountCenterResponse> accountCenter(@Validated AccountCenterRequest request, HttpServletRequest httpServletRequest){
        request.setMerId(getMerId(httpServletRequest));
        return CommonResult.success(channelMerchantAccountService.accountCenter(request));
    }

    @ApiOperation(value = "账户中心查看详情")
    @GetMapping(value = "/account/info/{id}")
    public CommonResult<Object> accountInfo(@PathVariable("id") Integer id){
        return CommonResult.success(channelMerchantAccountService.accountInfo(id,false));
    }

    /**
     * 获取平台收款账户
     * @return
     */
    @ApiOperation(value = "获取平台收款账户")
    @GetMapping(value = "/payment/account")
    public CommonResult<PaymentAccountRequest> PaymentAccount(){
        return CommonResult.success(channelMerchantService.PaymentAccount());
    }

    /**
     * 查询账户信息
     * @return
     */
    @ApiOperation(value = "查询账户信息")
    @GetMapping(value = "/getMerchant")
    public CommonResult<ChannelMerchantVO> getMerchant(HttpServletRequest httpServletRequest){
        return CommonResult.success(channelMerchantService.getMerchantById(getMerId(httpServletRequest)));
    }

    @ApiOperation(value = "获取商户发货地")
    @GetMapping(value = "/stockArea")
    public CommonResult<List<StockAreaTempEnum>> getStockArea(HttpServletRequest servletRequest){
        return CommonResult.success(channelMerchantService.getStockArea(getMerId(servletRequest)));
    }

    @ApiOperation(value = "获取商户配置")
    @GetMapping(value = "/config/detail")
    public CommonResult<ChannelMerchantVO> getMerchantConfigDetail(HttpServletRequest request){
        return CommonResult.success(channelMerchantService.getMerchantConfigDetail(getMerId(request)));
    }

    @ApiOperation(value = "供应商账户中心")
    @GetMapping(value = "/account/center/supplier")
    public CommonResult<SupplierAccountCenterResponse> accountCenterSupplier(PageParamRequest pageParamRequest, HttpServletRequest httpServletRequest){
        return CommonResult.success(channelMerchantAccountService.supplierAccountCenter(getMerId(httpServletRequest),pageParamRequest));
    }

    @ApiOperation(value = "商户分销设置")
    @PostMapping(value = "/distribution/install")
    public CommonResult<String> installDistribution(@RequestBody @Validated DistributionRequest request, HttpServletRequest httpServletRequest){
        if(request.getModel() != 1){
            if(Objects.isNull(request.getApplyType())){
                return CommonResult.validateFailed("请选择适用商品");
            }
            if(request.getCondition().compareTo(BigDecimal.ZERO)<1){
                return CommonResult.validateFailed("达成条件不能小于等于0");
            }
            if(request.getApplyType() == 2 && Objects.isNull(request.getSpecifyConditions())){
                return CommonResult.validateFailed("请选择指定条件");
            }
            if(request.getApplyType() == 3 && StringUtils.isBlank(request.getSpecifyGoods())){
                return CommonResult.validateFailed("请选择指定商品");
            }
        }
        return channelMerchantDistributionService.installDistribution(getMerId(httpServletRequest),request) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "商户兜底佣金设置")
    @PostMapping(value = "/baseRebateRate/update")
    public CommonResult<String> baseRebateRateUpdate(@RequestBody @Validated DistributionBaseRebateRequest request, HttpServletRequest httpServletRequest){

        return channelMerchantDistributionService.baseRebateRateUpdate(getMerId(httpServletRequest),request) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "查询商户分销设置")
    @GetMapping(value = "/distribution")
    public CommonResult<DistributionResponse> getDistribution(HttpServletRequest httpServletRequest){
        return CommonResult.success(channelMerchantDistributionService.getDistribution(getMerId(httpServletRequest)));
    }

    @ApiOperation(value = "查询商户小程序收款信息")
    @GetMapping(value = "/applet/account")
    public CommonResult<AppletAccountRequest> getAppletAccount(HttpServletRequest httpServletRequest){
        return CommonResult.success(channelMerchantAccountService.getAppletAccount(getMerId(httpServletRequest)));
    }

    @ApiOperation(value = "小程序收款信息设置")
    @PostMapping(value = "/applet/account/save")
    public CommonResult<String> saveAppletAccount(@RequestBody @Validated AppletAccountRequest request, HttpServletRequest httpServletRequest){
        return channelMerchantAccountService.saveAppletAccount(getMerId(httpServletRequest),request) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "购买产品与服务")
    @PostMapping(value = "/purchase")
    public CommonResult<Object> purchaseProduct(@RequestBody PurchaseProductRequest purchaseProductRequest, HttpServletRequest request) {
        purchaseProductRequest.setMerId(getMerId(request));
        return CommonResult.success(channelMerchantService.purchaseProduct(purchaseProductRequest, CrmebUtil.getClientIp(request)));
    }

    @ApiOperation(value = "订购列表")
    @GetMapping(value = "/purchase")
    public CommonResult<CommonPage<ChannelMerchantPurchaseResponse>> getPurchaseList(PageParamRequest request, HttpServletRequest servletRequest) {
        return CommonResult.success(channelMerchantService.getPurchaseList(getMerId(servletRequest), request));
    }

    @ApiOperation(value = "购买结果查询")
    @GetMapping(value = "/purchase/{orderId}")
    public CommonResult<ChannelMerchantPurchaseResponse> getPurchaseStatus(@PathVariable String orderId){
        return CommonResult.success(channelMerchantService.getPurchaseStatus(orderId));
    }

    @ApiOperation(value = "退款")
    @GetMapping(value = "/refund/{amount}/{orderId}")
    public CommonResult<Object> refund(@PathVariable BigDecimal amount, @PathVariable String orderId) {
        if (!refundFlag) {
            return CommonResult.success(channelMerchantService.refund(amount, orderId));
        } else {
            return CommonResult.failed();
        }

    }

}
